package nbcp.base.comm

import nbcp.base.extend.IntersectIndexes

//差异数据: T 表示第一个数据，R表示第2个数据。如： 123， 234 ，common = 23 , more = 1 , less = 4
data class DiffData<T, R> @JvmOverloads constructor(
    //公共索引,key=第一个数据索引， value = 第二个数据索引。
    var commonIndexMap: Map<Int, Int> = mapOf<Int, Int>(),
    //第一部分多出的数据
    var more1: List<T> = listOf<T>(),
    //第一部分公共数据
    var common1: List<T> = listOf<T>(),
    //第二部分公共数据
    var common2: List<R> = listOf<R>(),
    //第二部分多出的数据。
    var more2: List<R> = listOf<R>()
) {
    companion object {
        //把数据分隔为 DiffData，
        @JvmStatic
        inline fun <T, R> load(data: Iterable<T>, other: Collection<R>, equalFunc: (T, R) -> Boolean): DiffData<T, R> {
            var diff = DiffData<T, R>();

            var indexList = data.IntersectIndexes(other, equalFunc);

            var keyIndexList = indexList.keys;
            var valueIndexList = indexList.values;

            diff.commonIndexMap = indexList;
            diff.more1 = data.filterIndexed { index, _ -> keyIndexList.contains(index) == false };
            diff.common1 = data.filterIndexed { index, _ -> keyIndexList.contains(index) };
            diff.common2 = other.filterIndexed { index, _ -> valueIndexList.contains(index) };
            diff.more2 = other.filterIndexed { index, _ -> valueIndexList.contains(index) == false };
            return diff;
        }
    }

    fun isSame(): Boolean {
        if (this.more1.any()) return false;
        if (this.more2.any()) return false;

        return this.common1.size == this.common2.size;
    }
}